//
//  YFSensorManager.m
//  SquashSpark
//
//  Created by Coollang on 2017/11/9.
//  Copyright © 2017年 Coollang-YF. All rights reserved.
//

#import "YFSensorManager.h"
#import "YFAlertHelper.h"
#import "YFSportAndSensorApi.h"
#import "DeviceInfo.h"
#import "NSString+Extension.h"
#import "YFSportAndSensorApi.h"
#import "YFSportViewController.h"
#import "YFUserDefaults.h"
#import "YFMMDrawerStateManager.h"
#import "JCError.h"
#import <DateTools/DateTools.h>
#import "YFSearchController.h"
#import "YFSensorViewController.h"

@interface YFSensorManager()<UITextFieldDelegate>

@property (nonatomic, strong) NSTimer *autoCircleTimer;
@end

@implementation YFSensorManager

+ (instancetype)shareSensorManager {
    static YFSensorManager *_instance;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        _instance = [[YFSensorManager alloc] init];
    });
    return _instance;
}

// 打开设备操作页面或链接页面
+ (void)openSensorControllrWithVc:(UIViewController *)vc isNecessaryOpenSensorVc:(BOOL)isNecessaryOpenSensorVc;  {
    if (![YFCommunicationManager shareInstance].isCentralReady) {
        // 弹框
        return;
    }
    if (isNecessaryOpenSensorVc && [vc isKindOfClass:[YFSensorViewController class]] == NO) {
        YFSensorViewController *sensorVc = [YFSensorViewController sensorViewControllerWithType:kSensorConnect];
        sensorVc.hidesBottomBarWhenPushed = YES;
        [vc.navigationController pushViewController:sensorVc animated:YES];
    }else {
        if ([YFCommunicationManager shareInstance].isPeripheralConnected == NO) {
            YFSearchController *searchVc = [[UIStoryboard storyboardWithName:@"Sensor" bundle:nil] instantiateViewControllerWithIdentifier:@"YFSearchController"];
            searchVc.hidesBottomBarWhenPushed = YES;
            [vc.navigationController pushViewController:searchVc animated:YES];
        }else {
            YFSensorViewController *sensorVc = [YFSensorViewController sensorViewControllerWithType:kSensorConnect];
            sensorVc.hidesBottomBarWhenPushed = YES;
            [vc.navigationController pushViewController:sensorVc animated:YES];
        }
    }
    
}


- (void)readBattery:(void(^)(BOOL success,NSInteger battery))block {
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeBatteryRead parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
        if ([[response allKeys] containsObject:@"bleDesc"]) {
            NSInteger battery = [response[@"bleDesc"][@"battery"] integerValue];
            if (block) {
                block(YES,battery);
            }
        }else {
            block(NO,-1);
        }
    }];
}

- (void)cleanDeviceCache:(Completed)block {
    [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeCleanData parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
        if (block) {
            block(success);
        }
    }];
}
#pragma mark - 连接或断开连接
- (void)connectThePeripheral:(LGPeripheral *)peripheral completed:(BleConnectBlock)block
{
    [[YFCommunicationManager shareInstance] connectPeripheral:peripheral completion:^(BOOL success, NSError *error) {
        if (success) {
            // 0.保存
            [DeviceInfo deviceWithPer:peripheral];
            // 1.校准时间戳
            [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeVerify parmaObject:nil completionBlock:^(BOOL success, id response, NSError *error) {
                // 2.校准左右手
                [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeHand parmaObject:@([User getUseInfo].handBallType) completionBlock:^(BOOL success, id response, NSError *error) {
                    if (block) {
                        block(success,error);
                    }
                }];
            }];
        }else {
            if (block) {
                block(success,error);
            }
        }
    }];
}
// 断开设备连接
- (void)disconnect:(BOOL)showAlert callback:(void(^)(BOOL success))block {
    if (showAlert) {
        [YFAlertHelper showTwoAlertController:[YFMMDrawerStateManager sharedManager].drawerController.centerViewController Title:@"Warm Prompt" message:@"Disconnect the current connection?" cancelTitle:@"Cancel" defalutTitle:@"Confirm" defaultBtnStyle:UIAlertActionStyleDestructive cancelAction:^(UIAlertAction *action) {
            
        } defalutAction:^(UIAlertAction *action) {
            [[YFCommunicationManager shareInstance] disconnectThePeripheralWithCompletionBlock:^(BOOL success, NSError *error) {
                if (block) {
                    block(success);
                }
            }];
        }];
    }else {
        [[YFCommunicationManager shareInstance] disconnectThePeripheralWithCompletionBlock:^(BOOL success, NSError *error) {
            if (block) {
                block(success);
            }
        }];
    }
}
#pragma mark - 设备升级
- (void)checkSensorUpadteWithParent:(UIViewController *)parentVc locationversion:(void(^)(BOOL versionSuccessful, NSString *version,NSInteger battery))locationVersion {
    [self getLocationDeviceVersionAndBattery:^(BOOL versionSuccessful, NSString *version, NSInteger battery) {
        if (locationVersion) {
            locationVersion(versionSuccessful,version,battery);
        }
        if (versionSuccessful) {
            [YFSportAndSensorApi getServerDeviceVersionWithOemTpe:[YFCommunicationManager shareInstance].lgPeripheral.oemType completed:^(NSString *versionS, NSString *downloadPath, NSError *error) {
                if (error == nil) {
                    // 判断版本号
                    if ([NSString checkIsLastestVersion:versionS lastestVersion:version]) {
                        // 2. 判断电量
                        // 3.弹窗或直接点击升级
                    }
                }
            }];
        }
    }];
}

- (void)getLocationDeviceVersionAndBattery:(VersionBlock)block {
    
    [[YFCommunicationManager shareInstance] getDeviceVersionAndBatteryDatawithCompletion:^(BOOL versionSuccessful, NSString *version, NSInteger battery) {
        if (versionSuccessful) {
            DeviceInfo *device = [DeviceInfo getLastDevice];
            [[RLMRealm defaultRealm] beginWriteTransaction];
            device.locationVersion = version;
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }
        if (block) {
            block(versionSuccessful,version,battery);
        }
    }];
}

#pragma mark - 修改设备名称
- (void)changeDeviceNameCallback:(void(^)(BOOL success,NSString *newName))changeNameBlock {
    if (![YFCommunicationManager shareInstance].isPeripheralConnected) {
        if (changeNameBlock) {
            changeNameBlock(NO,nil);
        }
        return;
    }
    UIAlertController *alertVc = [UIAlertController alertControllerWithTitle:@"Device name" message:@"Please enter a new device name" preferredStyle:UIAlertControllerStyleAlert];
    [alertVc addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
         textField.text = [[YFCommunicationManager shareInstance].lgPeripheral.name removewBegianAndEndWhitespaceCharcterSet];
         //去掉名字的首尾空格
         textField.delegate = self;
         textField.textAlignment = NSTextAlignmentLeft;
    }];
    UITextField *textField = alertVc.textFields.firstObject;
//    textField.text = [YFCommunicationManager shareInstance].lgPeripheral.name;
//    textField.textAlignment = NSTextAlignmentLeft;
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        if (changeNameBlock) {
            changeNameBlock(NO,textField.text);
        }
    }];
    [alertVc addAction:cancelAction];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"Confirm" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSString *newName = [textField.text removewBegianAndEndWhitespaceCharcterSet];
        [[YFCommunicationManager shareInstance] requestOperationType:OperationTypeChangeDeviceName parmaObject:[textField.text removewBegianAndEndWhitespaceCharcterSet] completionBlock:^(BOOL success, id response, NSError *error) {
            if (success) {
                [[YFSensorManager shareSensorManager] disconnect:NO callback:^(BOOL success) {
                    [[YFCommunicationManager shareInstance] reconnetDeviceCompletion:^(BOOL success, NSError *error) {
                        // 修改设备成功
                        if (changeNameBlock) {
                            changeNameBlock(YES,newName);
                        }
                    }];
                }];
            }else {
                if (changeNameBlock) {
                    changeNameBlock(NO,nil);
                }
            }
        }];
        
    }];
    [alertVc addAction:confirmAction];
    AppDelegate *appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    UIViewController *controller = appdelegate.window.rootViewController;
    [controller presentViewController:alertVc animated:YES completion:nil];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (string.length > 0 && textField.text.length > 17) {
        [MBProgressHUD showTextHUDWithMessage:NSLocalizedString(@"Name required less than 17 letters or numbers", nil) inView:nil afterDelay:1.2];
        return NO;
    }else if ([string isEqualToString:@"\n"]){
        return NO;
    }
    return YES;
}
#pragma mark - 蓝牙数据同步逻辑
/**
 读取日期数组中所有的日期详情数据
 @params    statisticArray   硬件获取回来的统计数据
 1 --【1】：新用户、新安装的APP,本地未存有连接过的设备mac地址 和 数据：
 只要大于账户创建时间的数据
 保存当前连接设备的mac地址
 保存最新一拍最为断点
 
 【2】：老用户、新安装的APP,本地只有数据：
 只要大于账户创建时间的数据 && 本地未存有时间的数据 && 今天的数据（覆盖替换掉服务器和本地的）
 保存当前连接设备的mac地址
 保存最新一拍为断点
 【3】：正常状态下的用户、本地有连接过的 mac地址、 数据、 断点：
 只要大于账户创建时间的数据 && 本地未存有时间的数据 && 今天的数据（覆盖替换掉服务器和本地的）
 保存当前连接设备的mac地址
 保存最新一拍为断点
 */
- (void)getSwingWithStatisticArray:(NSArray *)statisticArray
                      mainComplete:(void (^)(BOOL, NSError *))mainCompletion
                     swingProgress:(void(^)(CGFloat))progress
                    swingCompelete:(void (^)(BOOL, NSError *))swingCompletion {
    
    NSInteger swingCount = 0;
    UserType userType = [[User getLastUser] userType];
    
    NSInteger creatTimestamp;
    if (kFiltEarlyData == 1) {
        ///账号创建日期
        creatTimestamp = [[NSDate formateYearMonthDayString:[User getUseInfo].createTime] timeIntervalSince1970];
    }else{
        creatTimestamp = [[NSDate formateYearMonthDayString:@"2017-12-01"] timeIntervalSince1970];
    }
    
    NSMutableArray *resultStatisticArray = [NSMutableArray array];
    ///1.过滤掉 小于账号创建时间的数据
    for (YFDayRecordItem *dayItem in statisticArray) {
        if (dayItem.dateTimeStamp >= creatTimestamp) {
            [resultStatisticArray addObject:dayItem];
        }
    }
    NSArray *resultArray = [resultStatisticArray copy];
    
    NSInteger todayTimstamp = [[NSDate new] timeIntervalSince1970] / 86400;
    
    ///数据库中已有的统计模型
    RLMResults *allHaveStatistic = [YFDayRecordItem getUserAllDayRecordItems];
    
    switch (userType) {
        case UserTypeNewUserNewApp:
            // 只过滤掉 小于账号创建时间的数据
            break;
        case UserTypeOldUserNewApp:{
            ///过滤掉 小于账号创建时间的数据 && 已经有的数据
            for (YFDayRecordItem *dayItem in resultArray) {
                if (allHaveStatistic.count > 0) {
                    if (dayItem.dateTimeStamp/86400 != todayTimstamp && [allHaveStatistic objectsWhere:@"dateTimeStamp == %lld",dayItem.dateTimeStamp].count > 0){
                        [resultStatisticArray removeObject:dayItem];
                    }
                }
            }
        }
            break;
        case UserTypeNormal:{
            ///过滤掉 小于账号创建时间的数据 && 已经有的数据
            for (YFDayRecordItem *dayItem in resultArray) {
                if (allHaveStatistic.count > 0) {
                    if (dayItem.dateTimeStamp/86400 != todayTimstamp && [allHaveStatistic objectsWhere:@"dateTimeStamp == %lld",dayItem.dateTimeStamp].count > 0){
                        [resultStatisticArray removeObject:dayItem];
                    }
                }
            }
        }
            break;
        case UserTypeError:{
            NSCAssert(nil, @"同步数据获取账户类型错误！");
        }
        default:
            break;
    }
    resultArray = [resultStatisticArray mutableCopy];
    [resultStatisticArray removeAllObjects];
#pragma mark - 到此、需要同步的数据，已经筛选出来，将统计数据存于数据库
    for (YFDayRecordItem *item in resultArray) {
        swingCount += item.dayAmountOfCount;
    }
    // 4.将数据写入本地
    RLMRealm *realm = [RLMRealm defaultRealm];
    ///判断是否切换了设备（本地未保存MAC地址时，默认为切换了设备，需要将重新同步今天的数据）
    [realm beginWriteTransaction];
    [realm commitWriteTransaction];
}


- (void)getBlueHomeDataWithComplete:(void(^)(NSArray<YFDayRecordItem *> *sportRecordItems, NSError *error))completed {
    if ([YFCommunicationManager shareInstance].isPeripheralConnected) {
        [[YFCommunicationManager shareInstance] getHomePageDataWithCallBlock:^(NSArray<YFDayRecordItem *> *sportRecordItems, NSError *error) {
            if (error == nil) {
                NSArray *resultArr = [self getSwingWithStatisticArray:sportRecordItems];
                if (completed) {
                    completed(resultArr,nil);
                }
            }else {
                if (completed) {
                    completed(nil,error);
                }
            }
        }];
    }else {
        if (completed) {
            completed(nil,[NSError errorWithDomain:@"Sensor Not connect" code:567]);
        }
    }
}

- (NSArray *)getSwingWithStatisticArray:(NSArray *)statisticArray {
    NSInteger creatTimeStamp;
    if (kFiltEarlyData == 1) {
        ///账号创建日期
        [NSDate formateYearMonthDayString:nil];
        creatTimeStamp = [[NSDate formateYearMonthDayString:[User getUseInfo].createTime] timeIntervalSince1970] / 86400;
    }else{
        creatTimeStamp = [[NSDate formateYearMonthDayString:@"2017-12-01"] timeIntervalSince1970] / 86400;
    }
    
    // 1.过滤掉 小于账号创建时间的数据
    NSMutableArray *statctisticArrM = [NSMutableArray array];
    for (YFDayRecordItem *dayItem in statisticArray) {
        if (dayItem.dateTimeStamp/86400 >= creatTimeStamp) {
             [statctisticArrM addObject:dayItem];
        }
    }
    // 2.覆盖今天的数据，过滤已经有的数据
    RLMResults *allHaveStatistic = [YFDayRecordItem getUserAllDayRecordItems];
    NSInteger todayTimstamp = [[NSDate new] timeIntervalSince1970] / 86400;
    for (YFDayRecordItem *dayItem in statctisticArrM.mutableCopy) {
        if (allHaveStatistic.count > 0) {
            if (dayItem.dateTimeStamp/86400 != todayTimstamp && [allHaveStatistic objectsWhere:@"dayDate == %@",dayItem.dayDate].count > 0){
                [statctisticArrM removeObject:dayItem];
            }
        }
    }
    return statctisticArrM.copy;
}

/*
 * 同步天的统计详情数据
 * everydayProgroess:具体的某一天的进度数据
 * allDayProgress: 总的进度
 * swingCompletion: 同步完成
 */
- (void)syncSwingDayDetailDataWithDayItems:(NSArray <YFDayRecordItem *>*)dayItems everydayProgress:(void(^)(YFDayRecordItem *dayItem,CGFloat dayProgress))everydayProgress allDayProgress:(void(^)(CGFloat totalProgress))allDayProgress compelete:(void (^)(void))completion {
    NSInteger swingCount = 0;
    if (dayItems.count == 0) {
        if (completion) {
            completion();
        }
        return;
    }
    for (YFDayRecordItem *item in dayItems) {
        swingCount += item.dayAmountOfCount;
    }
    __block NSInteger readedCount = 0;
    DeviceInfo *deviceInfo = [DeviceInfo getLastDevice];
    [[RLMRealm defaultRealm] transactionWithBlock:^{
        // 4.将数据写入本地
        deviceInfo.isNewChangeConnect = NO;
        deviceInfo.syncSwingDataTimeStamp = [[NSDate date] unixTimeStampWithDateStr];
        [User getLastUser].syncDataTimeStamp = [[NSDate date] unixTimeStampWithDateStr];
        // 将同步的数据存入数据库
        [[RLMRealm defaultRealm] addOrUpdateObjects:dayItems];
        
    }];
    
    [self getDetailData:dayItems array:nil index:0 everydayProgress:^(CGFloat dayProgress, NSArray *readDetailItems, YFDayRecordItem *dayItem) {
        if (everydayProgress) {
            everydayProgress(dayItem,dayProgress);
        }
        // 计算总的进度
        CGFloat totalProgress = (readedCount + dayItem.detailItems.count + readDetailItems.count) /(swingCount * 1.0);
        if (allDayProgress) {
            allDayProgress(totalProgress);
        }
    } completed:^(NSInteger index,YFDayRecordItem *dayItem) {
        if (dayItems.count > index) {
            readedCount += dayItem.detailItems.count;
        }
        if (index == dayItems.count - 1) {
            // 发送指令将数据同步上传到网络上
            [[NSNotificationCenter defaultCenter] postNotificationName:kuploadBlueDataToServer object:nil];
            if (completion) {
                completion();
            }
        }
    }];
}

// 获取详情数据
/**
 * detailIemArr: 空数组用于接受数据,直接传nil
 */
- (void)getDetailData:(NSArray <YFDayRecordItem *>*)dayItemArr array:(NSMutableArray *)detailIemArr index:(NSInteger)index everydayProgress:(void(^)(CGFloat dayProgress, NSArray *readDetailItems,YFDayRecordItem *dayItem))everydayProgress completed:(void(^)(NSInteger index,YFDayRecordItem *dayItem))completed {
    if (dayItemArr.count <= index) {
        if (completed) {
            completed(index,nil);
        }
        return;
    }
    YFDayRecordItem *dayItem = dayItemArr[index];
    if (dayItem.isSyncDetailReportData) {
        if (completed) {
            completed(index,dayItem);
        }
        return;
    }
    __weak typeof(self) weakSelf = self;
    if (detailIemArr == nil) {
        detailIemArr = [NSMutableArray array];
    }
    [[YFCommunicationManager shareInstance] getSwingDetailItemWithDay:dayItem.dateTimeStamp indexJ:dayItem.detailItems.count + detailIemArr.count CallBlock:^(YFSwingDetailItem *swingDetailItem, NSError *error) {
        if (swingDetailItem) {
          // 详情数据的时间戳可能会重复
//          [dayItem.detailItems addObject:swingDetailItem];
            [detailIemArr addObject:swingDetailItem];
//        [dayItem addDetailItem:swingDetailItem isUpdate:YES];
        }
        CGFloat percent = (dayItem.detailItems.count * 1.0)/dayItem.dayAmountOfCount;
        if (everydayProgress) {
            everydayProgress(percent,detailIemArr.copy,dayItem);
        }
    } readCompleted:^(BOOL success) {
        if (dayItem.detailItems.count + detailIemArr.count < dayItem.dayAmountOfCount) {
            [weakSelf getDetailData:dayItemArr array:detailIemArr index:index everydayProgress:everydayProgress completed:nil];
        }else {
            [[RLMRealm defaultRealm] transactionWithBlock:^{
                [dayItem addDetailItems:detailIemArr isOpenTransaction:NO];
                // 记得一定要调用下一步
                [dayItem calculateStatisticsValue];
                dayItem.isSyncDetailReportData = YES;
            }];
            if (index < dayItemArr.count - 1) {
                [weakSelf getDetailData:dayItemArr array:nil index:index + 1 everydayProgress:everydayProgress completed:completed];
            }
            if (completed) {
                completed(index,dayItem);
            }
        }
    }];
}

#pragma mark - 将数据上传到网络
- (void)uploadHomeData:(void(^)(NSError *error))homeDataCompleted andHomeDetailData:(void(^)(NSError *error))detailDatacompleted {
    [self updloadHomeDataToServerCompleted:^(NSError *error) {
        [self uploadDetailDataToServerCompleted:^(NSError *error) {
            
        }];
    }];
}

- (void)updloadHomeDataToServerCompleted:(void(^)(NSError *error))completed {
    // 1.找出需要上传数据
    RLMResults *results = [YFDayRecordItem getUserAllDayRecordItems];
    // 本地更新的时间戳大于网络时间戳，则需要上传
    results = [results objectsWhere:@"locationUpdateTime > serverUpdateTime"];
    if (results.count <= 0) {
        if (completed) {
            completed(nil);
        }
        return;
    }
    [YFSportAndSensorApi uploadDayRecordDataWithItems:(NSArray *)results completed:^(NSError *error) {
        if (error == nil) {
            [[RLMRealm defaultRealm] beginWriteTransaction];
            for (YFDayRecordItem *dayItem in results) {
                NSLog(@"%@",dayItem);
                dayItem.serverUpdateTime = dayItem.locationUpdateTime;
            }
            [[RLMRealm defaultRealm] commitWriteTransaction];
        }
        if (completed) {
            completed(error);
        }
    }];
}
- (void)uploadDetailDataToServerCompleted:(void(^)(NSError *error))completed {
    // 1.找出需要上传数据
    RLMResults *results = [YFDayRecordItem getUserAllDayRecordItems];
    NSMutableArray *arrM = [NSMutableArray array];
    for (YFDayRecordItem *dayItem in results) {
        if (dayItem.isSyncDetialToServer == NO && dayItem.detailItems.count > 0) {
            [arrM addObject:dayItem];
        }
    }
    if (arrM.count <= 0) {
        if (completed) {
            completed(nil);
        }
        return;
    }
    [YFSportAndSensorApi uploadDayRecordDetailDataWithDayItem:(NSArray *)arrM completed:^(NSError *error) {
        if (error == nil) {
            [[RLMRealm defaultRealm] transactionWithBlock:^{
                for (YFDayRecordItem *dayItem in arrM) {
                    dayItem.isSyncDetialToServer = YES;
                    dayItem.serverUpdateTime = dayItem.locationUpdateTime;
                }
            }];
            if (completed) {
                completed(nil);
            }
        }else {
            if (completed) {
                completed(error);
            }
        }
    }];
}

// 将服务器上的主页数据，数据同步到本地
- (void)sysnHomeDataFromServerCallBlock:(void(^)(BOOL sysSuccess))callBlock {
    dispatch_async(dispatch_queue_create("downLoadHomeData",DISPATCH_QUEUE_SERIAL), ^{
        // 1.获取有数据天的数据
        YFSportAndSensorApi *haveDataDaysApi = [YFSportAndSensorApi getHaveSportDataDays];
        [[YFNetworkingService sharedInstance] sendRequest:haveDataDaysApi callback:^(BOOL success, id result, NSError *error) {
            if (success) {
                NSArray *daysArr = [haveDataDaysApi responseInfo];
                // 1.判断本地是否已经有该天的数据
                // 2.获取最新上传的时间戳
                // NSInteger lastUpdateTime = [YFUserDefaults lastUpdateTime];
                // 本地有统计数据的话
                RLMResults *allDayItems = [YFDayRecordItem getUserAllDayRecordItems];
                NSMutableArray *arrM = [NSMutableArray arrayWithArray:daysArr];
                [daysArr enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    if ([allDayItems objectsWhere:@"dayDate == %@",obj].count > 0) {
                        [arrM removeObject:obj];
                    }
                }];
                // 3.下载统计数据
                if (arrM.count >0) {
                    NSMutableArray *apiArrM = [NSMutableArray arrayWithCapacity:arrM.count];
                    [arrM enumerateObjectsUsingBlock:^(NSString *_Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                        YFSportAndSensorApi *getHomeDataApi = [YFSportAndSensorApi getDayStatisticsDataWithDay:obj];
                        [apiArrM addObject:getHomeDataApi];
                    }];
                    [[YFNetworkingService sharedInstance] sendBatch:apiArrM.copy callback:^(BOOL success, YTKBatchRequest *resultT, NSError *error) {
                        if (success) {
                            NSLog(@"%@",resultT.requestArray);
                            NSMutableArray *dayItemsArrM = [NSMutableArray array];
                            for (YFSportAndSensorApi *api in resultT.requestArray) {
                                YFDayRecordItem *dayItem = [[YFDayRecordItem alloc] init];
                                [dayItem dayRecordItemFormServerDict:[api responseInfo]];
                                if (dayItem.identification != nil) {
                                    [dayItemsArrM addObject:dayItem];
                                }
                                //[YFDayRecordItem saveDayRecoedItemToDocument:dayItem update:NO];
                            }
                            // 存入数据库
                            RLMRealm *realm = [RLMRealm defaultRealm];
                            [realm beginWriteTransaction];
                            [realm addOrUpdateObjects:dayItemsArrM.copy];
                            [realm commitWriteTransaction];
                            if (callBlock) {
                                callBlock(success);
                            }
                        }else {
                            if (callBlock) {
                                callBlock(success);
                            }
                        }
                    }];
                }else {
                    if (callBlock) {
                        callBlock(YES);
                    }
                }
            }else {
                if (callBlock) {
                    callBlock(NO);
                }
            }
        }];
 });
    
}


#pragma mark - 循环重连模块
- (void)circulationReconnect {
    if ([YFCommunicationManager shareInstance].shouldRetryConnect == YES) {
        [self autoCircleTimer];
    }
}
- (void)timerAction {
    [self autoReconnectDeviceCallback:^(BOOL recSuc) {
        if (recSuc) {
            [self removeTimer];
        }
    }];
}
- (void)autoReconnectDeviceCallback:(void(^)(BOOL recSuc))reconnectBlock {
    if ([YFCommunicationManager shareInstance].shouldRetryConnect == NO) {
        reconnectBlock(NO);
        [self removeTimer];
        return;
    }
    NSString *UUIDString = [YFCommunicationManager shareInstance].lgPeripheral.UUIDString;
    if (UUIDString == nil || UUIDString.length <= 0) {
        reconnectBlock(NO);
        [self removeTimer];
        return;
    }
    NSUUID *uuid = [[NSUUID alloc] initWithUUIDString:UUIDString];
    if (uuid == nil) {
        reconnectBlock(NO);
        [self removeTimer];
        return;
    }
    [[YFCommunicationManager shareInstance] reConnectPeripheralUUID:uuid completion:^(BOOL success, NSError *error) {
        if (reconnectBlock) {
            reconnectBlock(success);
        }
    }];
}
- (void)removeTimer {
    [self.autoCircleTimer invalidate];
    self.autoCircleTimer = nil;
}
- (NSTimer *)autoCircleTimer {
    if (_autoCircleTimer == nil) {
        _autoCircleTimer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_autoCircleTimer forMode:NSRunLoopCommonModes];
    }
    return _autoCircleTimer;
}


@end
